package com.yxq.mdt.app.modules.auction.ui;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ToastUtils;
import com.orhanobut.hawk.Hawk;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.modules.auction.model.AuctionModel;
import com.yxq.mdt.app.modules.personal.bean.AddressBean;
import com.yxq.mdt.app.net.ApiModel;
import com.yxq.mdt.app.utils.CheckIdCard;
import com.yxq.mdt.app.utils.StringUtils;
import com.yxq.mdt.app.widgets.CustomAddressPicker;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.qqtheme.framework.entity.City;
import cn.qqtheme.framework.entity.County;
import cn.qqtheme.framework.entity.Province;

/**
 * 申请成为区县代理资料录入页面
 * Lior
 * 2020.4.12
 */
public class CountyLeaderApplyActivity extends BaseActivity {


    @BindView(R.id.apply_et_name)
    EditText applyEtName;
    @BindView(R.id.apply_et_card)
    EditText applyEtCard;
    @BindView(R.id.apply_tv_area)
    TextView applyTvArea;
    @BindView(R.id.apply_tv_tel)
    EditText applyTvTel;
    @BindView(R.id.apply_btn_submit)
    Button applyBtnSubmit;
    private boolean hideProvince = false;
    private boolean hideCounty = false;
    private String selectedProvince = "", selectedCity = "", selectedCounty = "";
    ArrayList<Province> provinceArrayList = new ArrayList<>();
    String addressId;
    String selectedProvinceId = "", selectedCityId = "", selectedCountyId = "";

    @Override
    public int getLayoutId() {
        return R.layout.activity_county_leader_apply;
    }

    @Override
    public void initView() {

    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        //加载缓存的区域数据
        List<AddressBean> addressBeanList = null;
        String address = Hawk.get("addressList", null);
        if (address != null) {
            addressBeanList = JSON.parseArray(address, AddressBean.class);
        }
        if (addressBeanList != null) {
            parseAddressList(addressBeanList);
        }
    }

    @OnClick({R.id.apply_btn_submit, R.id.apply_tv_area})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.apply_tv_area:
                addressPickView();
                break;
            case R.id.apply_btn_submit:
                submit();
                break;
        }
    }

    /**
     * 发起申请区县代理
     */
    private void submit() {
        if (applyEtName.getText().toString().trim().length() == 0) {
            ToastUtils.showLong("请填写真实姓名");
            return;
        }
        if (applyEtCard.getText().toString().trim().length() == 0) {
            ToastUtils.showLong("请填写身份证号");
            return;
        }
        if (!CheckIdCard.check(applyEtCard.getText().toString().trim())) {
            ToastUtils.showLong("请填写合法的身份证号");
            return;
        }
        if (applyTvArea.getText().toString().trim().length() == 0) {
            ToastUtils.showLong("请选择您要代理的区县");
            return;
        }
        if (applyTvTel.getText().toString().trim().length() == 0) {
            ToastUtils.showLong("请填写手机号");
            return;
        }
        if (!StringUtils.isMobileExact(applyTvTel.getText())) {
            ToastUtils.showShort("请输入合法的手机号码");
            return;
        }
        showLoadingDialog();
        AuctionModel.becomeArea(applyEtName.getText().toString(), applyEtCard.getText().toString(), selectedCountyId, applyTvTel.getText().toString(), new ApiModel.CommonCallback<String>() {
            @Override
            public void onSuccess(String s) {
                hideLoadingDialog();
                JSONObject jsonObject = JSON.parseObject(s);
                int status = jsonObject.getIntValue("state");
                if (status == 1) {
                    ToastUtils.showLong("申请成功,审核成功将会收到短信通知。");
                    finish();
                } else {
                    ToastUtils.showLong("申请失败");
                }

            }

            @Override
            public void onError(String errMsg) {
                hideLoadingDialog();
                ToastUtils.showLong(errMsg);
            }
        });
    }

    /**
     * 处理地区数据
     *
     * @param addressBeanList
     */
    private void parseAddressList(List<AddressBean> addressBeanList) {
        for (AddressBean addressBean : addressBeanList) {
            Province province = new Province(addressBean.getId() + "", addressBean.getName());
            List<AddressBean.ListBeanX> listBeanXES = addressBean.getList();
            List<City> cityList = new ArrayList<>();
            for (AddressBean.ListBeanX cityBean : listBeanXES) {
                City city = new City(cityBean.getId() + "", cityBean.getName());
                List<AddressBean.ListBeanX.ListBean> listBeanList = cityBean.getList();
                List<County> countyList = new ArrayList<>();
                for (AddressBean.ListBeanX.ListBean CountyBean : listBeanList) {
                    countyList.add(new County(CountyBean.getId() + "", CountyBean.getName()));
                }
                city.setCounties(countyList);
                cityList.add(city);
            }
            province.setCities(cityList);
            provinceArrayList.add(province);
        }
    }

    /**
     * 选择地址弹出框
     */
    private void addressPickView() {
        if (provinceArrayList.size() == 0) {
            showLoadingDialog();
            return;
        }
        CustomAddressPicker picker = new CustomAddressPicker(this, provinceArrayList);

        /** 显示几列 **/
        picker.setHideProvince(hideProvince);
        picker.setHideCounty(hideCounty);

        /** 标题区域 **/
        picker.setTopBackgroundColor(getResources().getColor(R.color.white));//设置标题背景颜色
        picker.setTopHeight(60);//设置顶部标题栏高度（单位为dp）

        picker.setCancelText("取消");
        picker.setCancelTextSize(14);
        picker.setCancelTextColor(getResources().getColor(R.color.color_font_black));//设置顶部标题栏取消按钮文字颜色
        picker.setCancelVisible(true);//设置左边按钮是否显示

        picker.setTitleText("所在地区");//标题栏
        picker.setTitleTextSize(14);//标题栏大小
        picker.setTitleTextColor(getResources().getColor(R.color.color_font_black));//设置所在区域颜色

        picker.setSubmitText("完成");//设置标题右边文字
        picker.setSubmitTextSize(14);//设置完成按钮大小
        picker.setSubmitTextColor(getResources().getColor(R.color.color_font_black));//设置完成按钮颜色

        /**  标题与列表的分割线 **/
        picker.setTopLineColor(getResources().getColor(R.color.white));
        picker.setTopLineVisible(true);
        picker.setTopLineHeight(10);

        /** 列表区域 **/
        picker.setTextSize(14);//字体大小
        picker.setTextColor(getResources().getColor(R.color.black));//设置省市县字体滚动颜色
        picker.setDividerColor(getResources().getColor(R.color.white));//设置分割线的颜色
        picker.setLineSpaceMultiplier(4);
        /** 弹框消失的设置 **/
        picker.setCancelable(true);//false：必须选择后弹框才消失，true：点击框外可弹框消失


        /** 列的比重 **/
        if (hideCounty) {
            picker.setColumnWeight(0.8f, 1.0f);
        } else if (hideProvince) {
            picker.setColumnWeight(1.0f, 0.8f);
        } else {
            picker.setColumnWeight(1.0f, 1.0f, 1.0f);
        }

        picker.setSelectedItem(selectedProvince, selectedCity, selectedCounty);//设置默认
        picker.setOnAddressPickListener((Province province, City city, County county) -> {
            showLoadingDialog();
            AuctionModel.hasArea(county.getAreaId(), new ApiModel.CommonCallback<String>() {
                @Override
                public void onSuccess(String s) {
                    hideLoadingDialog();
                    //0 不存在区县代理 可以申请 1 已存在区县代理 不能申请
                    JSONObject jsonObject = JSON.parseObject(s);
                    int isExist = jsonObject.getIntValue("isExist");
                    if (isExist == 1) {
                        ToastUtils.showLong("该区县已存在区县代理 不能申请");
                        return;
                    }
                    selectedProvinceId = province.getAreaId();
                    selectedProvince = province.getAreaName();
                    selectedCityId = city.getAreaId();
                    selectedCity = city.getAreaName();
                    selectedCountyId = county.getAreaId();
                    selectedCounty = county.getAreaName();
                    applyTvArea.setText(String.format("%s %s %s", province.getAreaName(), city.getAreaName(), county.getAreaName()));
                }

                @Override
                public void onError(String errMsg) {
                    hideLoadingDialog();
                    ToastUtils.showLong(errMsg);
                }
            });

        });
        picker.show();
    }
}
